/**
 * 管理员管理系统 - 管理员仪表盘逻辑
 * 功能：查看用户、删除用户、监控订单
 */

class AdminDashboard {
    constructor() {
        this.currentUser = null;
        this.allUsers = [];
        this.currentFilter = 'all';
        this.dailyOrders = [];
        this.init();
    }

    init() {
        this.checkAuth();
        this.bindEvents();
        this.loadDashboardData();
    }

    // 检查用户认证状态
    checkAuth() {
        const user = JSON.parse(localStorage.getItem('currentUser'));
        console.log('当前用户:', user);
        
        if (!user || user.user_type !== 'Admin') {
            console.log('用户未登录或不是管理员，跳转到首页');
            window.location.href = 'index.html';
            return;
        }
        this.currentUser = user;
        document.getElementById('userName').textContent = user.username;
        console.log('管理员认证成功:', user.username);
    }

    // 绑定事件
    bindEvents() {
        // 用户菜单
        const userMenuBtn = document.getElementById('userMenuBtn');
        const userDropdown = document.getElementById('userDropdown');
        
        userMenuBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            userDropdown.classList.toggle('show');
        });

        document.addEventListener('click', () => {
            userDropdown.classList.remove('show');
        });

        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', () => {
            this.logout();
        });

        // 订单详情模态框关闭
        const closeOrderDetailModal = document.getElementById('closeOrderDetailModal');
        if (closeOrderDetailModal) {
            closeOrderDetailModal.addEventListener('click', () => {
                this.hideOrderDetailModal();
            });
        }

        const orderDetailModal = document.getElementById('orderDetailModal');
        if (orderDetailModal) {
            orderDetailModal.addEventListener('click', (e) => {
                if (e.target === orderDetailModal) {
                    this.hideOrderDetailModal();
                }
            });
        }
    }

    // 加载仪表盘数据
    async loadDashboardData() {
        try {
            this.showLoading();
            
            // 加载用户列表
            await this.loadUsers();
            
            // 加载每日订单统计
            await this.loadDailyOrders();
            
        } catch (error) {
            console.error('加载仪表盘数据失败:', error);
            this.showToast('加载数据失败', 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 加载用户列表
    async loadUsers() {
        try {
            console.log('开始加载用户列表...');
            const res = await api.getAdminUsers();
            
            if (!res.success) {
                console.error('获取用户列表失败:', res.error);
                throw new Error(res.error || '获取用户失败');
            }
            
            const data = res.data;
            this.allUsers = data.users || [];
            
            // 更新统计卡片
            document.getElementById('totalUsers').textContent = data.total || 0;
            document.getElementById('totalCustomers').textContent = data.customers || 0;
            document.getElementById('totalSellers').textContent = data.sellers || 0;
            
            // 渲染用户列表
            this.renderUsers();
            
            console.log('用户列表加载完成');
            
        } catch (error) {
            console.error('加载用户列表失败:', error);
            this.showToast('加载用户列表失败 / Load failed: ' + error.message, 'error');
        }
    }

    // 渲染用户列表
    renderUsers() {
        const usersBody = document.getElementById('usersBody');
        
        // 过滤用户
        let filteredUsers = this.allUsers;
        if (this.currentFilter !== 'all') {
            filteredUsers = this.allUsers.filter(u => u.user_type === this.currentFilter);
        }
        
            if (filteredUsers.length === 0) {
            usersBody.innerHTML = `
                <tr>
                    <td colspan="8" style="text-align: center; padding: 20px; color: #999;">
                        暂无用户 / No users
                    </td>
                </tr>
            `;
            return;
        }
        
        usersBody.innerHTML = filteredUsers.map(user => {
            const userTypeClass = {
                'Customer': 'customer-badge',
                'Seller': 'seller-badge',
                'Admin': 'admin-badge'
            }[user.user_type] || '';
            
            const userTypeText = {
                'Customer': '买家 / Customer',
                'Seller': '卖家 / Seller',
                'Admin': '管理员 / Admin'
            }[user.user_type] || user.user_type;
            
            // 格式化日期
            const createdDate = user.created_at ? 
                new Date(user.created_at).toLocaleDateString('zh-CN') : '-';
            
            // 判断是否可以删除（不能删除管理员，不能删除自己）
            const canDelete = user.user_type !== 'Admin' && 
                             user.username !== this.currentUser.username;
            
            return `
                <tr>
                    <td>${user.username}</td>
                    <td>${user.user_id || '-'}</td>
                    <td><span class="${userTypeClass}">${userTypeText}</span></td>
                    <td>${user.email || '-'}</td>
                    <td>${user.phone || '-'}</td>
                    <td style="font-family: monospace; color: #666;">${user.password || '******'}</td>
                    <td>${createdDate}</td>
                    <td>
                        ${canDelete ? `
                            <button class="btn btn-sm btn-danger" onclick="adminDashboard.deleteUser('${user.username}')">
                                <i class="fas fa-trash"></i>
                                删除 / Delete
                            </button>
                        ` : '<span style="color: #999;">不可删除 / Cannot Delete</span>'}
                    </td>
                </tr>
            `;
        }).join('');
    }

    // 过滤用户
    filterUsers(filter) {
        this.currentFilter = filter;
        
        // 更新按钮状态
        document.querySelectorAll('.filter-buttons .btn').forEach(btn => {
            btn.classList.remove('btn-primary');
            btn.classList.add('btn-outline');
            if (btn.getAttribute('data-filter') === filter) {
                btn.classList.remove('btn-outline');
                btn.classList.add('btn-primary');
            }
        });
        
        // 重新渲染
        this.renderUsers();
    }

    // 删除用户
    async deleteUser(username) {
        if (!confirm(`确定要删除用户 "${username}" 吗？此操作不可恢复！\nAre you sure you want to delete user "${username}"? This action cannot be undone!`)) {
            return;
        }
        
        try {
            this.showLoading();
            
            const res = await api.deleteAdminUser(username);
            
            if (!res.success) {
                throw new Error(res.error || '删除用户失败');
            }
            
            this.showToast(`用户 ${username} 已删除 / User ${username} deleted`, 'success');
            
            // 重新加载用户列表
            await this.loadUsers();
            
        } catch (error) {
            console.error('删除用户失败:', error);
            this.showToast('删除用户失败 / Delete failed: ' + error.message, 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 加载每日订单统计
    async loadDailyOrders() {
        try {
            console.log('开始加载每日订单统计...');
            const res = await api.getAdminDailyOrders();
            
            if (!res.success) {
                console.error('获取每日订单统计失败:', res.error);
                throw new Error(res.error || '获取订单统计失败');
            }
            
            const data = res.data;
            this.dailyOrders = data.daily_stats || [];
            
            // 更新汇总数据
            const summary = data.summary || {};
            document.getElementById('summaryTotalOrders').textContent = summary.total_orders || 0;
            document.getElementById('summaryTotalAmount').textContent = `¥${(summary.total_amount || 0).toFixed(2)}`;
            document.getElementById('summaryAvgAmount').textContent = `¥${(summary.avg_per_order || 0).toFixed(2)}`;
            document.getElementById('totalOrders').textContent = summary.total_orders || 0;
            
            // 渲染每日订单表格
            this.renderDailyOrders();
            
            console.log('每日订单统计加载完成');
            
        } catch (error) {
            console.error('加载每日订单统计失败:', error);
            this.showToast('加载每日订单统计失败 / Load failed: ' + error.message, 'error');
        }
    }

    // 渲染每日订单表格
    renderDailyOrders() {
        const dailyOrdersBody = document.getElementById('dailyOrdersBody');
        
            if (this.dailyOrders.length === 0) {
            dailyOrdersBody.innerHTML = `
                <tr>
                    <td colspan="4" style="text-align: center; padding: 20px; color: #999;">
                        暂无订单数据 / No order data
                    </td>
                </tr>
            `;
            return;
        }
        
        dailyOrdersBody.innerHTML = this.dailyOrders.map(day => {
            return `
                <tr>
                    <td>${day.date}</td>
                    <td>${day.order_count}</td>
                    <td>¥${day.total_amount.toFixed(2)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="adminDashboard.showOrderDetail('${day.date}')">
                            <i class="fas fa-eye"></i>
                            查看详情 / View Details
                        </button>
                    </td>
                </tr>
            `;
        }).join('');
    }

    // 显示订单详情
    showOrderDetail(date) {
        const dayData = this.dailyOrders.find(d => d.date === date);
        if (!dayData) return;
        
        const modal = document.getElementById('orderDetailModal');
        const content = document.getElementById('orderDetailContent');
        
        // 格式化订单列表
        const ordersHtml = dayData.orders.map(order => `
                <div class="order-detail-item">
                <div class="order-header">
                    <span class="order-number">订单号 / Order No.: ${order.order_number}</span>
                    <span class="order-status status-${order.status.toLowerCase()}">${this.getStatusText(order.status)}</span>
                </div>
                <div class="order-info">
                    <p><strong>用户 / User:</strong> ${order.username}</p>
                    <p><strong>商品数量 / Items:</strong> ${order.item_count}件 / ${order.item_count} items</p>
                    <p><strong>订单金额 / Amount:</strong> ¥${order.amount.toFixed(2)}</p>
                </div>
            </div>
        `).join('');
        
            content.innerHTML = `
            <h4 style="margin-bottom: 15px;">${date} 订单详情 / Order Details</h4>
            <p style="margin-bottom: 20px; color: #666;">
                共 ${dayData.order_count} 单，总金额 ¥${dayData.total_amount.toFixed(2)} / ${dayData.order_count} orders, Total: ¥${dayData.total_amount.toFixed(2)}
            </p>
            <div class="orders-list">
                ${ordersHtml}
            </div>
        `;
        
        modal.classList.add('show');
        document.body.style.overflow = 'hidden';
    }

    // 隐藏订单详情模态框
    hideOrderDetailModal() {
        const modal = document.getElementById('orderDetailModal');
        modal.classList.remove('show');
        document.body.style.overflow = '';
    }

    // 获取状态文本
    getStatusText(status) {
        const statusMap = {
            'Processing': '待处理 / Processing',
            'Shipped': '已发货 / Shipped',
            'Delivered': '已送达 / Delivered',
            'Cancelled': '已取消 / Cancelled'
        };
        return statusMap[status] || status;
    }

    // 退出登录
    logout() {
        localStorage.removeItem('currentUser');
        window.location.href = 'index.html';
    }

    // 显示加载状态
    showLoading() {
        document.getElementById('loading').classList.add('show');
    }

    // 隐藏加载状态
    hideLoading() {
        document.getElementById('loading').classList.remove('show');
    }

    // 显示消息提示
    showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = `toast toast-${type} show`;
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }
}

// 初始化管理员仪表盘
const adminDashboard = new AdminDashboard();

